package com.yunxin.admin.system.api.core.customer;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunxin.admin.system.application.RoleQueryService;
import com.yunxin.admin.system.infra.common.constant.SecurityConstants;
import com.yunxin.admin.system.infra.framework.security.util.SecurityUtils;
import com.yunxin.admin.system.infra.persistence.entity.SysRoleDO;
import com.yunxin.admin.system.infra.persistence.entity.SysUserRoleDO;
import com.yunxin.common.result.PageResult;
import com.yunxin.common.result.Result;
import com.yunxin.core.admin.domain.AdminTeam;
import com.yunxin.core.domain.model.team.Team;
import com.yunxin.core.customer.dto.*;
import com.yunxin.core.wechat.domain.WechatInfo;
import com.yunxin.core.wechat.service.WechatFollowCustomerService;
import com.yunxin.core.wechat.service.WechatInfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author zero°
 * @since 2023-06-08
 */
@Tag(name = "15.企业微信关联")
@Slf4j
@RestController
@RequestMapping("/core/v1/wechatInfo")
@RequiredArgsConstructor
public class wechatInfoController {

    @Autowired
    private WechatInfoService wechatInfoService;

    private final RoleQueryService roleQueryService;

    @Autowired
    private WechatFollowCustomerService wechatFollowCustomerService;

    @Operation(summary = "分页查询微信企业账号", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/wechatInfoPageQuery")
    public PageResult<WechatInfo> wechatInfoPageQuery(@Validated @RequestBody WechatInfoPageDto command) {
        // 每个商户管理员只能看自己商户的数据
        Long userId = SecurityUtils.X.getUser().getUserId();
        List<Long> listByUserId = roleQueryService.getRoleListByUserId(userId).stream().map(SysUserRoleDO::getRoleId).toList();
        SysRoleDO sysRoleDO = roleQueryService.getRoleByCode("BOKE_MERCHANT_USER");
        if(!listByUserId.isEmpty()) if (!listByUserId.contains(sysRoleDO.getId())) {
            return PageResult.success(null, 0);
        }
        Page<WechatInfo> wechatInfoVoPage = wechatInfoService.wechatInfoPageQuery(command);
        return PageResult.success(wechatInfoVoPage.getRecords(),wechatInfoVoPage.getTotal());
    }

    @Operation(summary = "查询该用户下的所有团队", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/teamPageQuery")
    public PageResult<AdminTeam>  teamPageQuery(@Validated @RequestBody TeamPageDto command) {
        // 每个商户管理员只能看自己商户的数据
        Long userId = SecurityUtils.X.getUser().getUserId();
//        List<Long> listByUserId = roleQueryService.getRoleListByUserId(userId).stream().map(SysUserRoleDO::getRoleId).toList();
//        SysRoleDO sysRoleDO = roleQueryService.getRoleByCode("BOKE_MERCHANT_USER");
//        if(!listByUserId.isEmpty()) if (!listByUserId.contains(sysRoleDO.getId())) {
//            return PageResult.success(null, 0);
//        }
        if (ObjectUtils.isEmpty(SecurityUtils.X.getUser().getMerchantId())){
            return PageResult.success(null, 0);
        }
        Page<AdminTeam> teamWechatVoPage = wechatInfoService.teamPageQuery(command,userId);
        return PageResult.success(teamWechatVoPage.getRecords(), teamWechatVoPage.getTotal());
    }


    @Operation(summary = "团队关联微信企业", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/addWechatInfoTeam")
    public Result addWechatInfoTeam(@Validated @RequestBody AddWechatInfoTeamDto command) {
        // 每个商户管理员只能看自己商户的数据
        Long userId = SecurityUtils.X.getUser().getUserId();
        List<Long> listByUserId = roleQueryService.getRoleListByUserId(userId).stream().map(SysUserRoleDO::getRoleId).toList();
        SysRoleDO sysRoleDO = roleQueryService.getRoleByCode("BOKE_MERCHANT_USER");
        if(!listByUserId.isEmpty()) if (!listByUserId.contains(sysRoleDO.getId())) {
            return Result.success();
        }
        wechatInfoService.addWechatInfoTeam(command);
        return Result.success();
    }



    @Operation(summary = "批量刷新企业微信客户", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PreAuthorize("@ss.hasPerm('boke:wechat:ref')")
    @PostMapping("/refWectCoustomerList")
    public Result<Map<String, String>> refreshWechatCoustomerList() {
        // 每个商户管理员只能看自己商户的数据
        Long userId = SecurityUtils.X.getUser().getUserId();
        Map<String, String> stringStringMap = wechatFollowCustomerService.refreshWechatCoustomerList(userId);
        return Result.success(stringStringMap);
    }

    @Operation(summary = "通过企微客户Id刷新企业微信客户", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PreAuthorize("@ss.hasPerm('boke:wechat:ref')")
    @PostMapping("/refWectCoustomerById")
    public Result refWectCoustomerById(@Validated @RequestParam("customerId") Long customerId) {
        // 每个商户管理员只能看自己商户的数据
        Long userId = SecurityUtils.X.getUser().getUserId();
        wechatFollowCustomerService.refWectCoustomerById(userId,customerId);
        return Result.success();
    }


}
